package com.jianyi.system.shiro;

import com.jianyi.common.Constants;
import com.jianyi.system.model.entity.SysUser;
import com.jianyi.system.service.user.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.security.MessageDigest;
import java.util.HashSet;
import java.util.Set;


public class ShiroRealm extends AuthorizingRealm {

    private UserService userService;

    @Override

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Long userId = (Long) getAvailablePrincipal(principalCollection);
        // 列举此用户所有的权限
        //List<Permission> permissions = userService.findUserPermissionByName(username);
        // List<SysUserRes> listRes = sysUserResService.getPermissionByNo(userNo) ;
        Set<String> strs = new HashSet<String>();
       /* Iterator<SysUserRes> it = listRes.iterator();
        while (it.hasNext()) {
            SysUserRes re=it.next();
            strs.add(re.getResUrl());
        }*/
        //  strs.add("/test");
        strs.add("/get");
        System.out.println("用户id：" + userId);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(strs);
        return authorizationInfo;
    }

    /**
     * 登陆验证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        SysUser sysUser = userService.findUser(token.getUsername());
        //根据登录名获取用户信息

        if (sysUser == null) {
            // 抛出 帐号找不到异常
            throw new UnknownAccountException();
        }
        // 判断帐号是否锁定
        if (Boolean.TRUE.equals(sysUser.getLocked())) {
            // 抛出 帐号锁定异常
            throw new LockedAccountException();
        }
        return new SimpleAuthenticationInfo(
                sysUser.getId(),
                sysUser.getPassword(),
                ByteSource.Util.bytes(sysUser.getUserName() + Constants.CREDENTIALS_SALT),
                getName());
    }

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

}
